package org.itworks.biodev.gui;

import java.awt.event.*;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

import javax.swing.*;

import org.itworks.biodev.model.*;
import org.itworks.helpers.*;

public class EditMeetingDialogView extends JDialog implements Observer {
	
	public final static int INIT_DAYS_COMBOBOX = 1;
	public static final int FILL_COMBOBOX_CUSTOMERS = 2;
	public static final int STATUS_IS_UPDATING = 3;
	public static final int SET_MEETING = 4;
	
	
	private EditMeetingDialogControler controler;
	
	private javax.swing.JButton cancelButton;
    private javax.swing.JComboBox curstomersListComboBox;
    private javax.swing.JLabel dateMeetingLabel;
    private javax.swing.JLabel editMeetingTitleLabel;
    private javax.swing.JLabel hostMeetingLabel;
    private javax.swing.JLabel hourMeetingLabel;
    private javax.swing.JTextField hourMeetingTextField;
    private com.toedter.calendar.JDateChooser meetingDateChooser;
    private javax.swing.JButton oKButton;
    private javax.swing.JButton searchForCustomerButton;
    private javax.swing.JLabel searchForCustomerLabel;
    private javax.swing.JTextField searchForCustomerTextField;
    
    private boolean isOK = false;
    
    public EditMeetingDialogView(EditMeetingDialogControler controler) {
    	this.controler = controler;
    	this.controler.getModel().addObserver(this);
    	
    	initComponents();
    	initHandlers();
    	
    	controler.viewLoaded();
    	
    	
    }
    
    
    public void initComponents() {
    	
    	setLocationRelativeTo(null);
    	
    	editMeetingTitleLabel = new javax.swing.JLabel();
        hostMeetingLabel = new javax.swing.JLabel();
        curstomersListComboBox = new javax.swing.JComboBox();
        searchForCustomerLabel = new javax.swing.JLabel();
        searchForCustomerTextField = new javax.swing.JTextField();
        searchForCustomerButton = new javax.swing.JButton();
        dateMeetingLabel = new javax.swing.JLabel();
        meetingDateChooser = new com.toedter.calendar.JDateChooser();
        hourMeetingLabel = new javax.swing.JLabel();
        hourMeetingTextField = new javax.swing.JTextField();
        oKButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Edition d'une r�union");
        setResizable(false);

        editMeetingTitleLabel.setFont(new java.awt.Font("Trebuchet MS", 1, 18));
        editMeetingTitleLabel.setText("Ajouter une r�union");

        hostMeetingLabel.setText("H�te :");

        curstomersListComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "a", "b", "c", "d" }));

        searchForCustomerLabel.setText("Recherche rapide par nom :");

        searchForCustomerButton.setText("Filtrer");

        dateMeetingLabel.setText("Date :");

        hourMeetingLabel.setText("Heure :");
        
        SimpleDateFormat hour = new SimpleDateFormat("HH:mm:ss");
        Date d = new Date();
        hourMeetingTextField.setText( hour.format(d) );
        meetingDateChooser.setDate(d);

        oKButton.setText("OK");

        cancelButton.setText("Annuler");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(editMeetingTitleLabel)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(dateMeetingLabel)
                                .addGap(18, 18, 18)
                                .addComponent(meetingDateChooser, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(hostMeetingLabel)
                                .addGap(18, 18, 18)
                                .addComponent(curstomersListComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(searchForCustomerLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(searchForCustomerTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(searchForCustomerButton, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(hourMeetingLabel)
                                .addGap(18, 18, 18)
                                .addComponent(hourMeetingTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(oKButton, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(editMeetingTitleLabel)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(hostMeetingLabel)
                    .addComponent(curstomersListComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(searchForCustomerLabel)
                    .addComponent(searchForCustomerTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(searchForCustomerButton))
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(dateMeetingLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 25, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(cancelButton)
                            .addComponent(oKButton)))
                    .addComponent(meetingDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(hourMeetingLabel)
                        .addComponent(hourMeetingTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        pack();
        
        // Extra init
    }// </editor-fold>
    
    public void initHandlers() {
    	this.searchForCustomerButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent actionEvent) {
				// TODO Auto-generated method stub
				controler.searchForCustomerButtonActionPerformed(actionEvent, searchForCustomerTextField.getText());
				
			}
    		
    	});
    	
    	this.oKButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent actionEvent) {
				// TODO Auto-generated method stub
				isOK = true;
				Date d = meetingDateChooser.getDate();
				StringTokenizer token = new StringTokenizer(hourMeetingTextField.getText(), ":");
				if(token.countTokens() == 3) {
					
					Calendar c = Calendar.getInstance();
					c.setTime(d);
					c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(token.nextToken()));
					c.set(Calendar.MINUTE, Integer.parseInt(token.nextToken()));
					c.set(Calendar.SECOND, Integer.parseInt(token.nextToken()));
					
					if(controler.okButtonActionPerformed(actionEvent, curstomersListComboBox.getSelectedIndex(), c.getTime())) {
						setVisible(false);
					}
				} else {
					JOptionPane.showMessageDialog(null, "Le format de l'heure est invalide !", "Erreur", JOptionPane.ERROR_MESSAGE);
				}
			}
    		
    	});
 
    	
    	this.cancelButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent actionEvent) {
				// TODO Auto-generated method stub
				setVisible(false);
			}
    		
    	});
    }

	@Override
	public void update(Observable srcObject, Object object) {
		// TODO Auto-generated method stub
		MVCNotification notification = (MVCNotification)object;
		int reason = notification.getReason();
		
		switch(reason) {
		case FILL_COMBOBOX_CUSTOMERS:
			fillComboBoxCustomers((Vector<Customer>)notification.getObject());
			break;
		
		case STATUS_IS_UPDATING:
			boolean isUpdating = ((String)notification.getObject()).equals("1") ? true : false;
			if(isUpdating) {
				editMeetingTitleLabel.setText("Modifier une r�union");
			} else {
				editMeetingTitleLabel.setText("Ajouter une r�union");
			}
			break;
			

		case SET_MEETING:
			Meeting m = (Meeting)notification.getObject();
			if(m != null) {
				try {
					meetingDateChooser.setDate(m.getDateTime());
					curstomersListComboBox.setSelectedIndex(
						comboBoxGetIndexOfByWholeName(
							m.getHoster().getLastName() + " " + m.getHoster().getFirstName()
						)
					);
					SimpleDateFormat hour = new SimpleDateFormat("HH:mm:ss");
					hourMeetingTextField.setText(hour.format(m.getDateTime()));
				} catch(Exception e) {
					e.printStackTrace();
				}
			}
				break;
		}
		
	}


	private void fillComboBoxCustomers(Vector<Customer> customers) {
		// TODO Auto-generated method stub
		this.curstomersListComboBox.removeAllItems();
		for(Customer c : customers) {
			this.curstomersListComboBox.addItem(c.toString());
		}
	}
	
	private int comboBoxGetIndexOfByWholeName(String whole) {
		int index = -1;
		for(int i = 0; i < curstomersListComboBox.getItemCount(); ++i) {
			if(curstomersListComboBox.getItemAt(i).toString().equals(whole)) {
				index = i;
				break;
			}
		}
		
		return index;
	}
	
	public boolean getIsOK() {
		return this.isOK;
	}

}
